const router = require('express').Router();

const db = require("../db.js")

// 搜索历史
router.get("/search", (req, res) => {
    db.query("SELECT * FROM search ORDER BY id DESC LIMIT 0,5", (error, data) => {
        if (error) {
            res.json({
                "code": "400"
            })
        } else {
            res.json({
                "code": "200",
                "data": data
            })
        }
    })
})

// 搜索，添加搜索历史
router.post("/search", (req, res) => {
    let search_names = req.body.search_names
    db.query("INSERT INTO search (search_name) VALUES (?)", search_names, (error, data) => {
        if (error) {
            console.log(error)
        } else {
            res.json({
                "code": "200"
            })
        }
    })
})

// 清空搜索历史
router.delete("/search", (req, res) => {
    db.query("Truncate TABLE search", (error, data) => {
        if (error) {
            console.log(error)
        } else {
            res.json({
                "code": "200"
            })
        }
    })
})

// 查询
router.post('/details', (req, res) => {
    let page = req.body.page || 1
    let per_page = req.body.per_page || 4
    let offset = (page - 1) * per_page
    let search_name = req.body.search_name
    db.query(`SELECT * FROM gm_shop_goods WHERE goods_name LIKE '%${search_name}%' LIMIT ${offset},${per_page}`, (error, data) => {
        if (error) {
            console.log(error)
        } else {
            res.json({
                "code": "200",
                "data":data
            })
        }
    })
})

// SELECT * FROM gm_shop_goods WHERE goods_name LIKE '%空调%';

module.exports = router